#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class SafeFile
{
public:
    //构造函数初始化资源
    SafeFile(FILE *fp)
    : _fp(fp)
    {
        cout << "SafeFile(FILE *)" <<endl;
        if(nullptr == _fp)
        {
            cout << "nullptr == _fp" << endl;
        }
    }

    //提供若干访问资源的方法
    void write(const string &msg)
    {
        fwrite(msg.c_str(), msg.size(), 1, _fp);
    }

    //析构函数释放资源
    ~SafeFile()
    {
        cout <<"~SafeFile()" << endl;
        if(_fp)
        {
            fclose(_fp);
            cout << "fclose(_fp)" << endl;
        }
    }
private:
    FILE *_fp;
};

void test()
{
    string msg = "hello,world\n";
    //利用了栈对象的生命周期管理资源，当栈对象在离开作用域
    //的时候，会执行析构函数,进行回收资源
    SafeFile sf(fopen("wd.txt", "a+"));//sf栈对象
    sf.write(msg);

}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

